<?php
/**
 * 地区数据适配服务
 * 提供oa_region到oa_area格式的数据转换
 */

namespace app\service;

use think\facade\Db;
use think\facade\Cache;

class RegionService
{
    /**
     * 缓存前缀
     */
    const CACHE_PREFIX = 'region_service_';
    
    /**
     * 将oa_region数据转换为oa_area兼容格式
     */
    public static function adaptToAreaFormat($regionData)
    {
        if (empty($regionData)) {
            return [];
        }
        
        // 解析经纬度
        $longitude = null;
        $latitude = null;
        if (!empty($regionData['lng_lat'])) {
            $coords = explode(',', $regionData['lng_lat']);
            if (count($coords) >= 2) {
                $longitude = trim($coords[0]);
                $latitude = trim($coords[1]);
            }
        }
        
        return [
            'id' => $regionData['id'],
            'pid' => $regionData['parent_id'],
            'name' => $regionData['name'],
            'shortname' => $regionData['name'], // 直接使用地区名称作为简称
            'longitude' => $longitude ?? '',
            'latitude' => $latitude ?? '',
            'level' => $regionData['level'],
            'sort' => $regionData['sort'] ?? 0,
            'status' => $regionData['status'] ?? 1,
            'initial' => $regionData['initial'],
            'pinyin' => $regionData['pinyin'],
            'citycode' => $regionData['citycode'],
            'adcode' => $regionData['adcode']
        ];
    }
    
    /**
     * 批量转换地区数据
     */
    public static function adaptBatchToAreaFormat($regionList)
    {
        if (empty($regionList)) {
            return [];
        }
        
        $result = [];
        foreach ($regionList as $region) {
            // 解析经纬度
            $longitude = null;
            $latitude = null;
            if (!empty($region['lng_lat'])) {
                $coords = explode(',', $region['lng_lat']);
                if (count($coords) >= 2) {
                    $longitude = trim($coords[0]);
                    $latitude = trim($coords[1]);
                }
            }
            
            $result[] = [
                'id' => $region['id'],
                'pid' => $region['parent_id'],
                'name' => $region['name'],
                'shortname' => $region['name'], // 直接使用地区名称作为简称
                'longitude' => $longitude ?? '',
                'latitude' => $latitude ?? '',
                'level' => $region['level'],
                'sort' => $region['sort'] ?? 0,
                'status' => $region['status'] ?? 1,
                'initial' => $region['initial'],
                'pinyin' => $region['pinyin'],
                'citycode' => $region['citycode'],
                'adcode' => $region['adcode']
            ];
        }
        
        return $result;
    }
    
    /**
     * 生成树形结构
     */
    public static function generateTree($list, $pid = 0)
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item['pid'] == $pid) {
                $children = self::generateTree($list, $item['id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
    
    /**
     * 获取缓存键
     */
    private static function getCacheKey($type, $params = [])
    {
        return self::CACHE_PREFIX . $type . '_' . md5(serialize($params));
    }
    
    /**
     * 清除相关缓存
     */
    public static function clearCache()
    {
        $keys = Cache::get(self::CACHE_PREFIX . 'keys', []);
        foreach ($keys as $key) {
            Cache::delete($key);
        }
        Cache::delete(self::CACHE_PREFIX . 'keys');
    }
    
    /**
     * 添加缓存键到管理列表
     */
    private static function addCacheKey($key)
    {
        $keys = Cache::get(self::CACHE_PREFIX . 'keys', []);
        if (!in_array($key, $keys)) {
            $keys[] = $key;
            Cache::set(self::CACHE_PREFIX . 'keys', $keys, 3600);
        }
    }
    
    /**
     * 获取地区树形结构（带缓存和性能优化）
     */
    public static function getRegionTree($level = 0, $parentId = 0)
    {
        $cacheKey = self::getCacheKey('tree', ['level' => $level, 'parent_id' => $parentId]);
        
        if (Cache::has($cacheKey)) {
            return Cache::get($cacheKey);
        }
        
        // 优化：只查询必要的字段，减少数据传输
        $where = [['status', '=', 1]]; // 只查询启用的地区
        
        if ($level > 0) {
            $where[] = ['level', '<=', $level];
        }
        if ($parentId > 0) {
            $where[] = ['parent_id', '=', $parentId];
        }
        
        // 优化：按层级和拼音首字母排序
        $list = Db::name('region')
            ->where($where)
            ->field('id, parent_id, level, name, initial, pinyin, citycode, adcode, lng_lat, sort, status')
            ->order('level asc, initial asc, name asc')
            ->limit(5000) // 限制返回数量，避免大数据量
            ->select()
            ->toArray();
        
        $adaptedList = self::adaptBatchToAreaFormat($list);
        $tree = self::generateTree($adaptedList);
        
        // 延长缓存时间到24小时，减少数据库查询
        Cache::set($cacheKey, $tree, 86400);
        self::addCacheKey($cacheKey);
        
        return $tree;
    }
    
    /**
     * 获取简化地区树（仅包含ID和名称，用于快速加载）
     */
    public static function getSimpleRegionTree($level = 0, $parentId = 0)
    {
        $cacheKey = self::getCacheKey('simple_tree', ['level' => $level, 'parent_id' => $parentId]);
        
        if (Cache::has($cacheKey)) {
            return Cache::get($cacheKey);
        }
        
        $where = [['status', '=', 1]];
        
        if ($level > 0) {
            $where[] = ['level', '<=', $level];
        }
        if ($parentId > 0) {
            $where[] = ['parent_id', '=', $parentId];
        }
        
        // 只查询必要字段，减少内存使用
        $list = Db::name('region')
            ->where($where)
            ->field('id, parent_id, level, name, initial, pinyin')
            ->order('level asc, initial asc, name asc')
            ->limit(5000)
            ->select()
            ->toArray();
        
        $tree = self::generateTree($list);
        
        Cache::set($cacheKey, $tree, 86400);
        self::addCacheKey($cacheKey);
        
        return $tree;
    }
}